@file:Suppress("DEPRECATION")

package com.wanban.download.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.wanban.download.NotificationReceiver
import com.wanban.download.R
import com.wanban.download.WBDownloadUtils
import com.wanban.download.db.DownloadEntity
import com.wanban.download.utils.DownloadConstants
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit


class DownloadService : Service() {

    private val binder = LocalBinder()

    inner class LocalBinder : Binder() {
        fun getService(): DownloadService = this@DownloadService
    }

//    private var serviceDisposable: Disposable? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("下载服务", "onStartCommand...")
        callStartForeground()
//        if (intent == null) return super.onStartCommand(intent, flags, startId)
//        val action = intent.getIntExtra(DownloadConstants.INTENT_KEY_SERVICE_ACTION, -1)
//        if (action <= -1) return super.onStartCommand(intent, flags, startId)
//        when (action){
//            // 恢复所有任务
//            0 -> {
//                WBDownloadUtils.downloadManager.resumeAllDownloads()
//            }
//            1 -> { // 新增任务
//                val task = intent.getParcelableExtra(DownloadConstants.INTENT_KEY_SERVICE_TASK) as DownloadEntity?
//                if(task != null) {
//                    // 当前下载中的任务总数
//                    WBDownloadUtils.downloadManager.startDownload(task)
//                }
//            }
//            2 -> { // 暂停下载
//                val url = intent.getStringExtra(DownloadConstants.INTENT_KEY_SERVICE_DOWNLOAD_URL)
//                if (url != null) {
//                    WBDownloadUtils.downloadManager.stopDownload(url)
//                }
//            }
//            3 -> { // 恢复下载
//                val url = intent.getStringExtra(DownloadConstants.INTENT_KEY_SERVICE_DOWNLOAD_URL)
//                if (url != null) {
//                    WBDownloadUtils.downloadManager.resumeDownload(url)
//                }
//            }
//            4 -> { // 删除下载
//                val url = intent.getStringExtra(DownloadConstants.INTENT_KEY_SERVICE_DOWNLOAD_URL)
//                if (url != null) {
//                    WBDownloadUtils.downloadManager.deleteDownload(url)
//                }
//            }
//        }

//        if (serviceDisposable == null) {
//            serviceDisposable = Flowable.interval(1, TimeUnit.MINUTES)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe({
//                    val hasAvailableTask = WBDownloadUtils.getUnSuccessTasks().isNotEmpty()
//                    Log.d("下载服务", "检查是否有可用任务 -> ${hasAvailableTask}...")
//                    if (!hasAvailableTask) {
//                        serviceDisposable?.dispose()
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                            stopForeground(STOP_FOREGROUND_REMOVE)
//                        } else {
//                            stopSelf()
//                        }
//                    }
//                }, {
//                    it?.printStackTrace()
//                })
//        }
        return super.onStartCommand(intent, flags, startId)
    }


    override fun onBind(intent: Intent?): IBinder {
        Log.d("下载服务", "onBind...")
        return binder
    }

    fun resumeAllDownloads(){
        WBDownloadUtils.downloadManager.resumeAllDownloads()
    }

    fun startDownload(task: DownloadEntity){
        WBDownloadUtils.downloadManager.startDownload(task)
    }

    fun resumeDownload(url: String){
        WBDownloadUtils.downloadManager.resumeDownload(url)
    }



    override fun onDestroy() {
        Log.e("DownloadService", "下载服务关闭....")
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager?
        manager?.cancel(1001)
        super.onDestroy()
//        serviceDisposable?.dispose()

    }

    private fun callStartForeground() {
        val id = "com.wanban.download.id" //这里的id里面输入自己的项目的包的路径
        val intent = Intent()
        intent.setClass(this, NotificationReceiver::class.java)
        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }
        val notification: NotificationCompat.Builder //创建服务对象
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(id, "Download", NotificationManager.IMPORTANCE_MIN)
            channel.enableLights(false)
            channel.setShowBadge(true)
            channel.lockscreenVisibility = Notification.VISIBILITY_SECRET
            manager.createNotificationChannel(channel)
            notification = NotificationCompat.Builder(this).setChannelId(id)
        } else {
            notification = NotificationCompat.Builder(this)

        }
        notification.setVibrate(null)
            .setSound(null)
            .setLights(0, 0, 0)
            .setContentTitle(DownloadConstants.SERVICE_TITLE).setContentText(DownloadConstants.SERVICE_CONTENT)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_download).setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setDeleteIntent(pendingIntent)
            .setOngoing(false) // 设置为持续通知，不能直接清除

        val builder = notification.build()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(1001, builder, FOREGROUND_SERVICE_TYPE_DATA_SYNC)
        } else {
            startForeground(1001, builder)
        }
    }
}